/*
 * Copyright 2009 eBusinessInformation
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.excilys.ymca.service.zencontact;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;

import roboguice.inject.InjectResource;
import android.util.Log;

import com.excilys.ymca.R;
import com.excilys.ymca.model.Contact;
import com.excilys.ymca.model.ZenContact;
import com.excilys.ymca.service.ContactService;
import com.excilys.ymca.service.exception.ServiceException;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import com.google.inject.Inject;
import com.google.inject.Provider;

public class ZenContactService implements ContactService {

	private static final String		TAG	= ZenContactService.class.getSimpleName();

	@Inject
	private Gson					gson;

	@Inject
	private Provider<HttpClient>	httpClientProvider;

	/**
	 * Url du serveur distant mettant à disposition la liste de contacts.
	 */
	@InjectResource(R.string.zencontact_host)
	private String					host;

	@Override
	public List<Contact> getContactList() throws ServiceException {

		HttpClient httpClient = httpClientProvider.get();

		String url = host + "/contact/listAsJson";

		HttpUriRequest request = new HttpGet(url);

		Reader reader = null;
		try {
			HttpResponse response = httpClient.execute(request);

			InputStream is = response.getEntity().getContent();

			reader = new InputStreamReader(is);

			return gson.fromJson(reader, new TypeToken<List<ZenContact>>() {}.getType());
		} catch (IOException e) {
			Log.e(TAG, "Could not get Json content", e);
			throw new ServiceException(R.string.io_exception_contact_service_zen);
		} catch (JsonParseException e) {
			Log.e(TAG, "Could not parse Json result", e);
			throw new ServiceException(R.string.parse_exception_contact_service_zen);
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					Log.e(TAG, "Error when closing reader", e);
				}
			}
		}

	}
}
